package com.example.androidxdemo.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.navigation.Navigation
import androidx.navigation.fragment.findNavController
import com.example.androidxdemo.R
import com.example.androidxdemo.databinding.FragmentExampleBBinding
import com.example.androidxdemo.viewModel.LoginViewModel
import kotlinx.android.synthetic.main.fragment_example_b.*

@Suppress("NON_EXHAUSTIVE_WHEN")
class ExampleBFragment : BaseFragment() {
    var binding: FragmentExampleBBinding? = null
    private val loginViewModel: LoginViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentExampleBBinding.inflate(inflater, container, false)
        return binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loginViewModel.authenticationState.observe(
            viewLifecycleOwner,
            Observer { authenticationState ->
                when (authenticationState) {
                    LoginViewModel.AuthenticationState.AUTHENTICATED -> {
                        login_state_des.text = "登录成功后，检测登录状态为成功后，直接导航到该页面，如需跳转到登录页面，点击该段文字以取消登录状态"
                    }
                    LoginViewModel.AuthenticationState.UNAUTHENTICATED -> {
                        if (loginViewModel.needPopUpTo.value!!) {
                            findNavController().popBackStack()
                        }else {
                            Navigation.findNavController(view).navigate(R.id.action_global_loginFragment)
                        }
                    }
                }
            })
        login_state_des.setOnClickListener {
            loginViewModel.logout()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
        loginViewModel.resetPopUpTo()
    }
}